package org.acghub.mtdb.xmlgen.maker.bean;

import org.acghub.mtdb.common.Bean;
import org.acghub.mtdb.common.Config;
import org.acghub.mtdb.common.ObjectUtil;
import org.acghub.mtdb.common.Var;
import org.acghub.mtdb.util.StringUtil;
import org.acghub.mtdb.xmlgen.Maker;

import java.io.PrintStream;

/**
 * @author zhouhe
 */
public class BeanEqualsMaker extends Maker<Bean> {
    private final PrintStream ps;
    private final String prefix;

    public BeanEqualsMaker(Bean inner, Config config, PrintStream ps, String prefix) {
        super(inner, config);
        this.ps = ps;
        this.prefix = prefix;
    }

    @Override
    public void make() throws Exception {
        ps.println(prefix + "@Override");
        ps.println(prefix + "public boolean equals(Object o) {");
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "if (null == o || !getClass().equals(o.getClass())) { return false; }");
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "if (this == o) { return true; }");
        ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "%s that = (%s) o;\n", inner().getName(), inner().getName());
        for (Var var : inner().getVars()) {
            ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "if (%s(this.%s, that.%s)) { return false; }\n", ObjectUtil.NOT_EQUALS, var.getName(), var.getName());
        }
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "return true;");
        ps.println(prefix + "}");
    }
}
